package com.hlg.xboot.model.sys;

import com.hlg.xboot.model.BaseModel;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang3.StringUtils;

import javax.persistence.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>Description:</p>
 *
 * @author gaol
 * @version 1.0
 * @date 2017/5/17
 */
@Entity
public class Role extends BaseModel {

    /**
     * 角色编号
     */
    @Column(nullable = false, length = 10)
    private Integer code;

    /**
     * 角色名称
     */
    @Column(nullable = false, length = 10)
    private String name;

    @OneToOne
    @JoinColumn(name= "uid")
    private SysUser user;

    public SysUser getUser() {
        return user;
    }

    public void setUser(SysUser user) {
        this.user = user;
    }

    /**
     * 角色权限
     */
    @JsonIgnore
    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "role_permisson",
            joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id", nullable = false),
            inverseJoinColumns = @JoinColumn(name = "permisson_id", referencedColumnName = "id", nullable = false))
    private List<Permission> permissions;

    public List<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<Permission> permissions) {
        this.permissions = permissions;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取权限code集合
     *
     * @return
     */
    @JsonIgnore
    public Set<String> getResourceCode() {
        Set<String> resSet = new HashSet<>();
        for (Permission resource : this.getPermissions()) {
            if (StringUtils.isNotEmpty(resource.getPath())) {
                resSet.add(resource.getPath());
            }
        }
        return resSet;
    }

    public String toString(){
        return StringUtils.join(this.getResourceCode(),",");
    }
}
